﻿using System.Diagnostics;
using System.IO;
using System.Numerics;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace LeiDacceshi
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        //private DispatcherTimer _timer;
        private bool mediaPlayerIsPlaying = false;
        int timer = 0;
        string[] mediaPath;
        [DllImport("user32.dll")]
        private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
        public MainWindow()
        {
            InitializeComponent();
            Init(); 
            this.Closed += (s, e) => {
                System.Environment.Exit(0);
            };
        }
        public void Init()
        {
            Cursor = Cursors.None;
            string screensize = System.IO.Path.Combine(Config.APP_BATH, "SetScreenSize.txt");//
            if (!File.Exists(screensize))
            {
                this.Width = (int)SystemParameters.PrimaryScreenWidth;
                this.Height = (int)SystemParameters.PrimaryScreenHeight; 
                // 如果文件不存在，创建并写入数据
                using (StreamWriter writer = File.CreateText(screensize))
                {
                    writer.Write($"{this.Width}/{this.Height}");
                }
                LeftBtn.Width = this.Width;
            }
            else
            {
                var sizefile = File.ReadAllText(screensize);
                var size = sizefile.Split('/');
                this.Width = string.IsNullOrEmpty(size[0]) ? (int)SystemParameters.PrimaryScreenWidth : int.Parse(size[0]);
                this.Height = string.IsNullOrEmpty(size[1]) ? (int)SystemParameters.PrimaryScreenHeight : int.Parse(size[1]);
                LeftBtn.Width=this.Width;
            } 
            mediaPath = Directory.GetFiles(Config.MediaPath, "*.mp4");
            mPlayer.Stretch = Stretch.Fill;
            //// 初始化定时器
            //_timer = new DispatcherTimer();
            //_timer.Interval = TimeSpan.FromSeconds(1);
            //_timer.Tick += Timer_Tick;
            //_timer.Start();
            mPlayer.MediaEnded += EndPlayFunaction;
            mPlayer.Loaded += PlayerLoad;
            mPlayer.Unloaded += PlayerUnLoad;
            SetPlayerUrl($"{mediaPath[0]}");
            Regeditkey.OnSetupStartupButtonClick("VPlayer");
        }
        public string GetMediaSource
        {
            get
            {
                return mPlayer.IsLoaded && mediaPlayerIsPlaying ? mPlayer.Source.ToString() : string.Empty;
            }
            set
            {
                //设置播放视频文件
                mPlayer.Source = new Uri(value); 
            }
        }
        private void PlayerUnLoad(object sender, RoutedEventArgs e)
        {
            mediaPlayerIsPlaying = false; 
        }

        private void PlayerLoad(object sender, RoutedEventArgs e)
        {
            mediaPlayerIsPlaying = true; 
        }

        private void EndPlayFunaction(object sender, RoutedEventArgs e)
        {
            if (GetMediaSource.Contains("2正片"))
            { 
                SetPlayerUrl($"{mediaPath[0]}");
            }
            else
            { 
                mPlayer.Stop();
                mPlayer.Play();
                mediaPlayerIsPlaying = true;
            }
        }

        public void SetPlayerUrl(string url)
        {

            var startindex = url.LastIndexOf('\\');
            var endindex = url.LastIndexOf('.');
            var strName = url.Substring(startindex + 1,
                          endindex - startindex - 1);

            if (string.IsNullOrEmpty(GetMediaSource))
            {
                mPlayer.Source = new Uri(url);
                mPlayer.Play();
                mediaPlayerIsPlaying = true;
            }
            else
            {
                if (GetMediaSource .Contains(strName))
                    return;
                mPlayer.Source = new Uri(url);
                mPlayer.Play(); 
                mediaPlayerIsPlaying = true;
            }
           
        }
        private void LeftBtn_Click(object sender, RoutedEventArgs e)
        { 
            SetPlayerUrl($"{mediaPath[1]}");
        }

        private void RightBtn_Click(object sender, RoutedEventArgs e)
        {
            //Console.WriteLine("点击右边");
            //SetPlayerUrl($"{Config.MediaPath}/东南三贤.mp4");
        }
        private void Timer_Tick(object sender, EventArgs e)
        {
            //// 重置计时器
            //_timer.Stop();
            //_timer.Start();

            // 检查系统是否超过60秒没有用户活动
            if (IsIdleFor60Seconds())
            {
               
               // SetPlayerUrl($"{Config.MediaPath}/屏保.mp4");
            }
            else
            {
               
               // SetPlayerUrl($"{Config.MediaPath}/东南三贤.mp4");
            }
        }

        private bool IsIdleFor60Seconds()
        {
            // 获取上一次输入的时间
            LASTINPUTINFO lastInputInfo = new LASTINPUTINFO();
            lastInputInfo.cbSize = (uint)Marshal.SizeOf(lastInputInfo);
            lastInputInfo.dwTime = 0;

            if (GetLastInputInfo(ref lastInputInfo))
            {
                // 计算时间差
                uint idleTime = (uint)Environment.TickCount - lastInputInfo.dwTime;
                return (idleTime >= Config.WAITFORTIMER); // 如果超过60秒，则返回true
            }
            else
            {
                throw new Exception("调用GetLastInputInfo失败");
            }
        }

        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            // 检查按下的键是否是空格键
            if (e.Key == Key.Escape)
            { 
                  Application.Current.Shutdown(); 
            }
            // 检查同时按下 Ctrl 和 P 键
            if (Keyboard.Modifiers == ModifierKeys.Control && e.Key == Key.P)
            {
                Regeditkey.OnCancelStartupButtonClick("VPlayer");
            }
            if (Keyboard.Modifiers == ModifierKeys.Control && e.Key == Key.I)
            {
                Regeditkey.OnSetupStartupButtonClick("VPlayer");
            }
        }
    } 
}